package com.erbadagang.springboot.mongodb.dao.impl;

import com.erbadagang.springboot.mongodb.dao.IErbadagangDao;
import com.erbadagang.springboot.mongodb.entity.ErbadagangEntity;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * @description 操作数据库的dao实现类。使用了MongoTemplate。
 * @ClassName: ErbadagangDaoImpl
 * @author: 郭秀志 jbcode@126.com
 * @date: 2020/8/8 17:06
 * @Copyright:
 */
@Repository
public class ErbadagangDaoImpl implements IErbadagangDao {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void saveDemo(ErbadagangEntity erbadagangEntity) {
        mongoTemplate.save(erbadagangEntity);
    }

    @Override
    public void removeDemo(Long id) {
        mongoTemplate.remove(id);
    }

    @Override
    public void updateDemo(ErbadagangEntity erbadagangEntity) {
        Query query = new Query(Criteria.where("id").is(erbadagangEntity.getId()));

        Update update = new Update();
        update.set("title", erbadagangEntity.getTitle());
        update.set("description", erbadagangEntity.getDescription());
        update.set("by", erbadagangEntity.getBy());
        update.set("url", erbadagangEntity.getUrl());

        mongoTemplate.updateFirst(query, update, ErbadagangEntity.class);
    }

    @Override
    public ErbadagangEntity findDemoById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        ErbadagangEntity erbadagangEntity = mongoTemplate.findOne(query, ErbadagangEntity.class);
        return erbadagangEntity;
    }

}

